import { Physics, Input } from "phaser";
import { Main, trackY } from "../Main";

export class Player extends Physics.Arcade.Sprite {
    // 是否投掷中（防止重复投掷）
    isThrowing: boolean = false;
    // 当前所处轨道序号
    trackIndex: number = 0;

    // 键盘对象
    spacebar: Input.Keyboard.Key;
    up: Input.Keyboard.Key;
    down: Input.Keyboard.Key;

    scene: Main = null;

    constructor(scene: Main) {
        // 创建对象
        super(scene, 900, trackY[0], "sprites", "idle000");
        this.scene = scene;
        scene.add.existing(this);
        scene.physics.add.existing(this);

        // 设置属性
        this.setOrigin(0.5, 1);
        this.spacebar = scene.input.keyboard.addKey(Input.Keyboard.KeyCodes.SPACE);
        this.up = scene.input.keyboard.addKey(Input.Keyboard.KeyCodes.UP);
        this.down = scene.input.keyboard.addKey(Input.Keyboard.KeyCodes.DOWN);

        // 玩家空闲动画
        this.play("idle");

        // 注册事件
        this.addEvent();
    }
    // 注册事件
    addEvent() {
        // 玩家投掷动画事件
        this.on("animationcomplete-throwStart", this.throwStart, this);
        this.on("animationcomplete-throwEnd", this.throwEnd, this);
    }
    preUpdate(time: number, delta: number) {
        super.preUpdate(time, delta);
        // 键盘事件
        if (Input.Keyboard.JustDown(this.up)) {
            this.moveUp();
        } else if (Input.Keyboard.JustDown(this.down)) {
            this.moveDown();
        } else if (Input.Keyboard.JustDown(this.spacebar) && !this.isThrowing) {
            this.throw();
        }
    }
    // 上移
    moveUp() {
        this.trackIndex = this.trackIndex == 0 ? 3 : this.trackIndex - 1;
        this.y = trackY[this.trackIndex];
        this.scene.sound.play("move");
    }
    // 下移
    moveDown() {
        this.trackIndex = this.trackIndex == 3 ? 0 : this.trackIndex + 1;
        this.y = trackY[this.trackIndex];
        this.scene.sound.play("move");
    }
    // 投掷
    throw() {
        this.isThrowing = true;
        this.play("throwStart");
        this.scene.sound.play("throw");
    }
    // 投掷开始
    throwStart() {
        this.play("throwEnd");
        // 回调回场景
        this.scene.throwPlayerBall();
    }
    // 投掷结束
    throwEnd() {
        this.isThrowing = false;
        this.play("idle");
    }
    // 停止
    stop() {
        this.play("die");
        this.disableBody(true);
        return this;
    }
}
